package com.weixin.program.utils;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;

import java.io.File;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @desc: <br/>
 * @author: Jingbo Hu<br/>
 * @time：2021年03⽉04⽇<br/>
 * @version：v1.0.0<br>
 */
public class ExcelUtil {

    private static final DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyyMMdd");

    public static void write(String sheetName, List datas, Class dataClass, String filePath, String imagepath) throws Exception {
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        //设置背景颜色
        headWriteCellStyle.setFillForegroundColor(IndexedColors.SKY_BLUE.getIndex());
        //设置头字体
        WriteFont headWriteFont = new WriteFont();
        headWriteFont.setFontHeightInPoints((short) 13);
        headWriteFont.setBold(true);
        headWriteCellStyle.setWriteFont(headWriteFont);
        //设置头居中
        headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        //内容策略
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        //设置 水平居中
        contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
        File file = new File(filePath);
        if (!file.exists()){
            file.mkdir();
        }
        String absolutePath = filePath + sheetName + ".xlsx";
        EasyExcel.write(absolutePath, dataClass).registerWriteHandler(horizontalCellStyleStrategy).sheet(sheetName).doWrite(datas);
        // Excel生成图片
        String date = LocalDate.now().format(fmt);
        imagepath = imagepath + date + ".png";
        Excel2ImageUtil.Excel2Image(absolutePath, imagepath);
    }
}
